//
//  ZZSearchPostCell.m
//  QQplayground
//
//  Created by zhangxy on 2018/7/5.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "ZZSearchPostCell.h"

#import <SDWebImage/UIImageView+WebCache.h>
#import "ZZShareView.h"

@implementation ZZSearchPostCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    _imgAvatar.layer.cornerRadius = 22.0f;
    _imgAvatar.layer.masksToBounds = YES;
    
    [_labTitle setFont:FontFiftent];
    _labTitle.numberOfLines = 0;
    [_labTitle setTextColor:UIColorFromRGB(TextSizeOneColor)];
    
    
    [_labName setFont:FontFiftent];
    [_labName setTextColor:UIColorFromRGB(TextSizeOneColor)];
    
    [_btnLevel.titleLabel setFont:ListElevenFont];
    _btnLevel.layer.cornerRadius = 4.0f;
    _btnLevel.layer.masksToBounds = YES;
    _btnLevel.layer.borderWidth = 1.0f;
    _btnLevel.layer.borderColor = UIColorFromRGB(BorderLineColor).CGColor;
    [_btnLevel setTitleColor:UIColorFromRGB(TextSizeOneColor) forState:0];
    [_btnLevel setImage:[UIImage imageNamed:@"收藏 小按钮"] forState:0];
    
    [_btnVip setBackgroundImage:[UIImage imageNamed:@"vip"] forState:0];
    
    [_labType setFont:FontThirteen];
    [_labType setTextColor:UIColorFromRGB(BgTitleColor)];
    
    [_labTime setFont:FontThirteen];
    [_labTime setTextColor:UIColorFromRGB(BgLineColor)];
    
    [self setBtnStype:_btnFav image:@"Combined_Shape"];
    [self setBtnStype:_btnComment image:@"Combined_Shape1"];
    [self setBtnStype:_btnStar image:@"Star_gray"];
    
    [self setBtnStype:_btnShare image:@"Combined_Shape2"];
    [_btnShare setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [_btnShare setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
}

-(void)setBtnStype:(UIButton *) btn image:(NSString *)imgName{
    [btn setImage:[UIImage imageNamed:imgName] forState:0];
    [btn setTitleColor:UIColorFromRGB(TextSizeOneColor) forState:0];
    [btn.titleLabel setFont:ListElevenFont];
    [btn setTitle:@"" forState:0];
    [btn setTitleEdgeInsets:UIEdgeInsetsMake(0, 2, 0, 0)];
    [btn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [btn setBackgroundColor:UIColor.clearColor];
    [btn addTarget:self action:@selector(onCotrolClick:) forControlEvents:UIControlEventTouchUpInside];
    
    btn.userInteractionEnabled = YES;
}

-(void)onCotrolClick:(UIButton *)btn{
    ZZTopicCellClickType type = 0;
    if([btn isEqual:_btnShare]){
        type = ZZClickShare;
    }else if([btn isEqual:_btnFav]){
        type = ZZClickFav;
    }else if([btn isEqual:_btnStar]){
        type = ZZClickStar;
    }else if([btn isEqual:_btnComment]){
        type = ZZClickComment;
    }
    
    if(_delegate && [self.delegate respondsToSelector:@selector(onCellItemClick:obj:)]){
        [self.delegate onCellItemClick:type obj:self.tempModel];
    }
}


-(void) moreComment:(UITapGestureRecognizer *) tap{
    if(_delegate && [self.delegate respondsToSelector:@selector(onCellItemClick:obj:)]){
        [self.delegate onCellItemClick:ZZClickComment obj:self.tempModel];
    }
}


-(void)dataToView:(ZZHomeTopicEntity *) topic{
    self.tempModel = topic;
    self.backgroundColor = UIColor.clearColor;
    [self setUserViewData:topic];
    [_imgBgView setBackgroundColor:UIColor.whiteColor];
    _imgBgView.layer.cornerRadius = 10.0f;
    _imgBgView.layer.masksToBounds = YES;
    
    self.viewContent.userInteractionEnabled = NO;
    
    CGRect uf = _imgBgView.frame;
    uf.size.height = CGRectGetMaxY(_viewControl.frame) + 10;
    _imgBgView.frame = uf;
    
    
    self.frame = CGRectMake(0, 0, ScreenWidth, CGRectGetMaxY(_imgBgView.frame)+10);
}

-(void)setUserViewData:(ZZHomeTopicEntity *) topic{
    [_imgAvatar sd_setImageWithURL:[NSURL URLWithString:convertToString(topic.user_info.user_avatar)] placeholderImage:[UIImage imageNamed:@"default_image"]];
    [_labName setText:topic.user_info.user_name];
    CGRect lf = _btnLevel.frame;
    [self autoWidthOfLabel:_labName with:21];
    lf.origin.x = CGRectGetMaxX(_labName.frame) + 5;
    _btnLevel.frame = lf;
    [_btnLevel setTitle:[NSString stringWithFormat:@"  Lv %@",topic.like_count] forState:0];
    [_btnLevel setContentEdgeInsets:UIEdgeInsetsMake(2, 0, 2, 0)];
    [_btnVip setFrame:CGRectMake(CGRectGetMaxX(lf) + 5, lf.origin.y, 52, 18)];
    [_labTime setText:topic.add_time];
    
    [_labTitle setText:topic.title];
    
    CGSize st = [self autoWidthOfLabelHegith:_labTitle with:ScreenWidth - 40];
    
    [self addContentToView:topic fy:CGRectGetMaxY(_labTitle.frame) + ((st.height>0)?10:0)];
    
    CGRect typeF = _labType.frame;
    typeF.origin.y = CGRectGetMaxY(_viewContent.frame) + 10;
    _labType.frame = typeF;
    [_labType setText:topic.nav_type];
    
    [self addCommentView:topic.thread_list fy:CGRectGetMaxY(typeF)+(topic.thread_list.count == 0 ? 0 : 10)];
    
    [_btnFav setTitle:[topic.like_count intValue] == 0 ? @"赞" : topic.like_count forState:0];
    [_btnComment setTitle:topic.thread_count == 0 ?@"评论":convertIntToString((int)topic.thread_count) forState:0];
    [_btnStar setTitle:[topic.fav_count intValue] == 0 ? @"收藏" : topic.fav_count forState:0];
    
    CGRect cf = _viewControl.frame;
    cf.origin.y = CGRectGetMaxY(_commentView.frame);
    if(topic.thread_list.count > 0){
        cf.origin.y = cf.origin.y + 10;
    }
    _viewControl.frame = cf;
}


-(CGFloat )createAvatarView:(ZZHomeTopicEntity *)topic{
    [_viewContent.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    CGFloat iw = 118;//((ScreenWidth - 20)*10)/30;
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 0, iw, iw)];
    [imgView sd_setImageWithURL:[NSURL URLWithString:topic.image_url] placeholderImage:[UIImage imageNamed:@"default_image"]];
    [_viewContent addSubview:imgView];
    
    
    return iw;
}


-(void)addContentToView:(ZZHomeTopicEntity *) topic fy:(CGFloat ) y{
    [_viewContent.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    if([@"sign" isEqual:topic.nav_type]){
        UILabel *lab = [self createLabel];
        [lab setFrame:CGRectMake(0, 0, ScreenWidth - 40, 0)];
        [lab setFont:FontFiftent];
        [lab setText:topic.message_1];
        CGSize s = [self autoWidthOfLabelHegith:lab with:ScreenWidth - 40];
        [_viewContent addSubview:lab];
        
        CGRect f = _viewContent.frame;
        f.origin.y = y;
        f.size.height = s.height;
        [_viewContent setFrame:f];
    }else if([@"name" isEqual:topic.nav_type]){
        UILabel *lab = [self createLabel];
        [lab setFrame:CGRectMake(0, 0, ScreenWidth - 40, 0)];
        [lab setText:topic.message_1];
        [lab setFont:FontFiftent];
        [lab setTextAlignment:NSTextAlignmentCenter];
        CGSize s = [self autoWidthOfLabelHegith:lab with:ScreenWidth - 40];
        [_viewContent addSubview:lab];
        CGFloat itemH = s.height;
        if(convertToString(topic.message_2).length > 0){
            UIImageView *lineView = [self createImageView];
            [lineView setBackgroundColor:UIColorFromRGB(BgLineColor)];
            [lineView setFrame:CGRectMake(0, s.height + 5 + 18, ScreenWidth - 40, 1)];
            [_viewContent addSubview:lineView];
            
            UIImageView *iconView = [self createImageView];
            [iconView setFrame:CGRectMake((ScreenWidth-40 - 36)/2, s.height + 5, 36, 36)];
            [iconView setImage:[UIImage imageNamed:@"情侣图标"]];
            [_viewContent addSubview:iconView];
            
            UILabel *lab2 = [self createLabel];
            [lab2 setFrame:CGRectMake(0, s.height + 10 + 36, ScreenWidth - 40, 0)];
            [lab2 setTextAlignment:NSTextAlignmentCenter];
            [lab2 setFont:FontFiftent];
            [lab2 setText:topic.message_2];
            [self autoWidthOfLabelHegith:lab2 with:ScreenWidth - 40];
            [_viewContent addSubview:lab2];
            
            
            itemH = CGRectGetMaxY(lab2.frame);
        }
        CGRect f = _viewContent.frame;
        f.origin.y = y;
        f.size.height = itemH;
        [_viewContent setFrame:f];
        
    }else if([@"group" isEqual:topic.nav_type]){
        // 34 128
        CGFloat x = 34;
        CGFloat iy = 0;
        CGFloat itemH = 65;
        CGFloat itemW = ScreenWidth - x - 40;
        
        NSArray *arr = topic.message_arr_1;
        for(NSString *str in arr){
            UILabel *label = [self createLabel];
            [label setFrame:CGRectMake(x+26, iy, itemW - 26, itemH)];
            [label setFont:FontFiftent];
            [label setText:str];
            CGSize s = [self autoWidthOfLabelHegith:label with:itemW - 26];
            if(s.height > itemH){
                itemH = s.height;
            }else{
                itemH = 65;
                [label setFrame:CGRectMake(x+26, iy, itemW - 26, itemH)];
            }
            
            UIImageView *aImg = [self createImageView];
            [aImg setImage:[UIImage imageNamed:@"icon_arrow"]];
            [aImg setContentMode:UIViewContentModeCenter];
            [aImg setFrame:CGRectMake(x, iy, 16, itemH)];
            
            
            UIImageView *lineView = [self createImageView];
            [lineView setBackgroundColor:UIColorFromRGB(BgLineColor)];
            [lineView setFrame:CGRectMake(x, iy + itemH - 0.5, itemW, 1)];
            
            
            iy = iy + itemH;
            
            [_viewContent addSubview:label];
            [_viewContent addSubview:aImg];
            [_viewContent addSubview:lineView];
        }
        
        UIImageView *imgView  = [self createImageView];
        [imgView setFrame:CGRectMake(0, 0, 34, iy)];
        [imgView setContentMode:UIViewContentModeCenter];
        [imgView setImage:[UIImage imageNamed:@"情侣"]];
        [_viewContent addSubview:imgView];
        
        CGRect f = _viewContent.frame;
        f.origin.y = y;
        f.size.height = iy;
        [_viewContent setFrame:f];
        
    }else{
        [self addContontImages:topic fy:y];
    }
    
    
}

-(void)addContontImages:(ZZHomeTopicEntity *)topic fy:(CGFloat ) y{
    [_viewContent.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    CGFloat maxWidth = ScreenWidth - 40;
    CGFloat space = 6;
    CGFloat minWidth = (ScreenWidth - 40 - space*2)/3;
    
    NSMutableArray *imgsObj = topic.images;
    if(imgsObj.count == 1 || [topic.nav_type isEqual:@"show"]){
        ImageEntity *firstObj = [imgsObj firstObject];
        UIImageView *imgView = [self createImageView];
        [imgView setFrame:CGRectMake(0, 0, maxWidth, maxWidth)];
        [imgView sd_setImageWithURL:[NSURL URLWithString:firstObj.image_url] placeholderImage:[UIImage imageNamed:@"default_image"]];
        
        if([topic.nav_type isEqual:@"show"]){
            UILabel *label =  [self createLabel];
            [label setFrame:CGRectMake(10, 10, 46, 24)];
            [label setTextAlignment:NSTextAlignmentCenter];
            [label setTextColor:UIColorFromRGB(TextWhiteColor)];
            [label setBackgroundColor:UIColorFromRGBAlpha(TextSizeOneColor, 0.2)];
            [label setText:[NSString stringWithFormat:@"%zdP",imgsObj.count]];
            [imgView addSubview:label];
        }
        
        [_viewContent addSubview:imgView];
    }else{
        CGFloat x = 0;
        
        for (int i = 0;i<imgsObj.count; i ++ ) {
            if(i==6){
                break;
            }
            ImageEntity *firstObj = imgsObj[i];
            UIImageView *imgView = [self createImageView];
            [imgView sd_setImageWithURL:[NSURL URLWithString:firstObj.image_url] placeholderImage:[UIImage imageNamed:@"default_image"]];
            imgView.layer.cornerRadius = 3.0f;
            imgView.layer.masksToBounds = YES;
            
            // 张图片居中
            if(imgsObj.count == 2){
                x = (maxWidth - minWidth * 2 - space * 2)/2;
                
                if(i==0){
                    [imgView setFrame:CGRectMake(x, 0, minWidth, minWidth)];
                }else{
                    [imgView setFrame:CGRectMake(x + space, 0, minWidth, minWidth)];
                }
            }else if(imgsObj.count == 4){
                // 张图片，第一个放大，其它居中
                if(i==0){
                    [imgView setFrame:CGRectMake(x, 0, maxWidth, 216)];
                }else{
                    [imgView setFrame:CGRectMake(x, 222, minWidth, minWidth)];
                    x = minWidth + x + space;
                }
            }else{
                // 换行，3 、4、6情况
                if(i <= 2){
                    [imgView setFrame:CGRectMake(x, 0, minWidth, minWidth)];
                }else{
                    [imgView setFrame:CGRectMake(x, minWidth + 6, minWidth, minWidth)];
                }
                
                //换行
                if(i == 2){
                    x = 0;
                }else{
                    x = minWidth + x + space;
                }
            }
            if(imgsObj.count > 6 && i == 5){
                UILabel *label =  [self createLabel];
                [label setFrame:imgView.bounds];
                [label setTextAlignment:NSTextAlignmentCenter];
                [label setTextColor:UIColorFromRGB(TextWhiteColor)];
                [label setText:[NSString stringWithFormat:@"%zdP",imgsObj.count]];
                [imgView addSubview:label];
            }
            [_viewContent addSubview:imgView];
        }
    }
    
    CGRect f = _viewContent.frame;
    f.origin.y = y;
    if(imgsObj.count == 1 || [topic.nav_type isEqual:@"show"]){
        f.size.height = maxWidth;
    }else if(imgsObj.count == 4){
        f.size.height = 216 + space + minWidth;
    }else{
        if(imgsObj.count <= 3){
            f.size.height = minWidth;
        }else{
            f.size.height = minWidth * 2 + space;
        }
    }
    [_viewContent setFrame:f];
}



-(UIImageView *)createImageView{
    UIImageView *imgView = [[UIImageView alloc] init];
    [imgView setContentMode:UIViewContentModeScaleAspectFill];
    imgView.clipsToBounds = YES;
    return imgView;
}

-(UILabel *) createLabel{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
    [label setTextAlignment:NSTextAlignmentLeft];
    [label setFont:FontThirteen];
    [label setTextColor:UIColorFromRGB(TextSizeOneColor)];
    [label setBackgroundColor:UIColor.clearColor];
    [label setNumberOfLines:0];
    return label;
}

-(void)addCommentView:(NSMutableArray *) array fy:(CGFloat) y{
    [_commentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    CGFloat iy = 10;
    if(array.count == 0){
        iy = 0;
    }
    for (ZZTopicCommentEntity *entity in array) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, iy, ScreenWidth - 60, 0)];
        [label setTextAlignment:NSTextAlignmentCenter];
        [label setFont:FontThirteen];
        [label setTextColor:UIColorFromRGB(TextSizeOneColor)];
        [label setBackgroundColor:UIColor.clearColor];
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@:%@",entity.user_info.user_name,entity.message]];
        CGFloat len = [NSString stringWithFormat:@"%@:",entity.user_info.user_name].length;
        [string addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(BgTitleColor) range:NSMakeRange(0, len)];
        
        [string addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(TextSizeOneColor) range:NSMakeRange(len, string.length - len)];
        label.attributedText = string;
        
        CGSize s = [self autoWidthOfLabelHegith:label with:label.frame.size.width];
        
        iy = s.height + iy + 7;
        [_commentView addSubview:label];
        
    }
    
    if(array.count > 2){
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, iy, ScreenWidth - 60, 21)];
        [label setTextAlignment:NSTextAlignmentCenter];
        [label setFont:FontThirteen];
        [label setTextColor:UIColorFromRGB(Text6Color)];
        [label setBackgroundColor:UIColor.clearColor];
        [label setText:@"查看全部评论..."];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(moreComment:)];
        [label addGestureRecognizer:tap];
        [_commentView addSubview:label];
        iy = iy + 21 + 10;
    }
    
    [_commentView setFrame:CGRectMake(10, y, ScreenWidth - 40, iy)];
    
}



/**
 计算Label高度
 
 @param label 要计算的label，设置了值
 @param width label的最大宽度
 */
- (CGSize )autoWidthOfLabel:(UILabel *)label with:(CGFloat )height{
    //Calculate the expected size based on the font and linebreak mode of your label
    // FLT_MAX here simply means no constraint in height
    CGSize maximumLabelSize = CGSizeMake(FLT_MAX, height);
    
    CGSize expectedLabelSize = [label sizeThatFits:maximumLabelSize];
    
    //adjust the label the the new height.
    CGRect newFrame = label.frame;
    newFrame.size.width = expectedLabelSize.width;
    label.frame = newFrame;
    [label updateConstraintsIfNeeded];
    
    return expectedLabelSize;
}

- (CGSize )autoWidthOfLabelHegith:(UILabel *)label with:(CGFloat )width{
    //Calculate the expected size based on the font and linebreak mode of your label
    // FLT_MAX here simply means no constraint in height
    CGSize maximumLabelSize = CGSizeMake(width, FLT_MAX);
    
    CGSize expectedLabelSize = [label sizeThatFits:maximumLabelSize];
    
    //adjust the label the the new height.
    CGRect newFrame = label.frame;
    newFrame.size.height = expectedLabelSize.height;
    label.frame = newFrame;
    [label updateConstraintsIfNeeded];
    
    return expectedLabelSize;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
